package com.joyoung.sweep.utils.Net;

import android.content.Intent;
import android.os.Build;

import com.joyoung.sdk.config.Cons_Sdk;
import com.joyoung.sweep.activity.login.LoginActivity;
import com.joyoung.sweep.base.JoyoungApplication;
import com.joyoung.sweep.config.Cons;
import com.joyoung.sweep.utils.AppUtils;
import com.joyoung.sweep.utils.CountEvent;
import com.joyoung.sweep.utils.MsgEvent;
import com.joyoung.sweep.utils.SPUtils;
import com.joyoung.sweep.utils.User;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * Application拦截器
 */
public class AppInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        String params = url.encodedQuery();
        Request build = request.newBuilder()
                .addHeader("sessionid", Cons_Sdk.sessionId == null ? "" : Cons_Sdk.sessionId)
                .addHeader("source", "1")
                .addHeader("model", Build.MANUFACTURER + Build.MODEL)
                .addHeader("localsizeModel", "Android")
                .addHeader("systemName", "Android" + Build.VERSION.RELEASE)
                .addHeader("systemVersion", String.valueOf(Build.VERSION.SDK_INT))
                .addHeader("mobileId", Cons.msdnForMobileId)
                .addHeader("mobileName", Build.MANUFACTURER)
                .addHeader("appversion", AppUtils.getVersion(JoyoungApplication.getAppContext()))
                .addHeader("appauthtoken", AppUtils.getAppToken(JoyoungApplication.getAppContext()))
                .build();
        Response response = chain.proceed(build);
        if (response.body() != null) {
            MediaType mediaType = response.body().contentType();
            String resultStr = response.body().string();
            switch (isTokenExpired(resultStr)) {
                case 0:
                    if (params != null && params.contains("getAppSplash")) {
                        EventBus.getDefault().post(new MsgEvent(CountEvent.INVALID_LOGIN, 0));
                        jumpToLoginPage();
                    }
                    break;
                case 1:
                    JoyoungApplication.getApplication().getToken();
                    break;
                default:
                    break;

            }

            ResponseBody responseBody = ResponseBody.create(mediaType, resultStr);
            return response.newBuilder().body(responseBody).build();
        } else {
            return response;
        }
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @return
     */
    private int isTokenExpired(String resultStr) {
        try {
            JSONObject jsonObject = new JSONObject(resultStr);
            String errCode = jsonObject.getString("code");
            return dispatchErrorCode(errCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 处理返回结果code
     *
     * @param errorCode
     * @return
     */
    private int dispatchErrorCode(String errorCode) {
        switch (errorCode) {
            case "10000":
            case "10001":
            case "10002":
            case "10003":
            case "10010":
            case "10011":
            case "1151":
                return 0;
            case "1401":
            case "1402":
                return 1;
            default:
                break;
        }
        return -1;
    }


    /**
     * 跳转到登录页
     */
    private void jumpToLoginPage() {
        Cons.sessionKey = null;
        Cons.user = null;
        User.delUser(JoyoungApplication.getAppContext());
        Intent intent = new Intent(JoyoungApplication.getAppContext(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        JoyoungApplication.getAppContext().startActivity(intent);
    }
}
